package com.zzr.zzrbackend.service.Impl;

import cn.hutool.core.convert.Convert;
import com.zzr.zzrbackend.config.JwtInterceptor;
import com.zzr.zzrbackend.mapper.EmergePersonMapper;
import com.zzr.zzrbackend.mapper.UserInfoMapper;
import com.zzr.zzrbackend.mapper.UserMapper;
import com.zzr.zzrbackend.mapper.VolunteerSortMapper;
import com.zzr.zzrbackend.pojo.domain.EmergePerson;
import com.zzr.zzrbackend.pojo.domain.ReviseEmergePersonParam;
import com.zzr.zzrbackend.pojo.domain.User;
import com.zzr.zzrbackend.pojo.domain.UserInfo;
import com.zzr.zzrbackend.pojo.dto.CommonResult;
import com.zzr.zzrbackend.pojo.dto.param.DeleteEmergePersonParam;
import com.zzr.zzrbackend.pojo.dto.param.EmergePersonParam;
import com.zzr.zzrbackend.pojo.dto.param.VolunteerParam;
import com.zzr.zzrbackend.pojo.dto.result.*;
import com.zzr.zzrbackend.service.MyInterfaceService;
import com.zzr.zzrbackend.util.TokenUtils;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MyInterfaceServiceImpl implements MyInterfaceService {
    @Resource
    UserMapper userMapper;
    @Resource
    UserInfoMapper userInfoMapper;
    @Resource
    private JwtInterceptor jwtInterceptor;
    @Resource
    HttpServletRequest request;
    @Resource
    EmergePersonMapper emergePersonMapper;
    @Resource
    VolunteerSortMapper volunteerSortMapper;

    @Override
    public CommonResult<ChildInterfaceResult> childHome() {

        Integer userId = jwtInterceptor.getUserId(request);
        User user = userMapper.selectById(userId);
        if (user == null) {
            return CommonResult.fail("用户不存在，数据库异常");
        }
        UserInfo userInfo =  userInfoMapper.selectByPrimaryKey(userId);
        if (userInfo == null) {
            return CommonResult.fail("数据库异常");
        }
        if(user.getPermission()!=1){
            return CommonResult.fail("权限异常，不是儿童权限");
        }
        ChildInterfaceResult childInterfaceResult = new ChildInterfaceResult();
        childInterfaceResult.setUserName(user.getUsername());
        childInterfaceResult.setHeadPicUrl(userInfo.getHeadPicUrl());

        // 下载和喜爱和我的消息， 暂时写死
        childInterfaceResult.setDownload(10);
        childInterfaceResult.setMyLove(50);
        childInterfaceResult.setMessageNumber(5);

        return CommonResult.success(childInterfaceResult);
    }

    @Override
    public CommonResult<ParentAndVolunteerFaceResult> parentHome() {

        Integer userId = jwtInterceptor.getUserId(request);
        User user = userMapper.selectById(userId);
        if (user == null) {
            return CommonResult.fail("用户不存在，数据库异常");
        }
        UserInfo userInfo =  userInfoMapper.selectByPrimaryKey(userId);
        if (userInfo == null) {
            return CommonResult.fail("数据库异常");
        }
        if(user.getPermission()!=2){
            return CommonResult.fail("权限异常，不是父母权限");
        }
        ParentAndVolunteerFaceResult parentAndVolunteerFaceResult = new ParentAndVolunteerFaceResult();
        parentAndVolunteerFaceResult.setUserName(user.getUsername());
        parentAndVolunteerFaceResult.setHeadPicUrl(userInfo.getHeadPicUrl());

        // 下载和喜爱和我的消息， 暂时写死
        parentAndVolunteerFaceResult.setMessageNumber(5);

        return CommonResult.success(parentAndVolunteerFaceResult);
    }

    @Override
    public CommonResult<ParentAndVolunteerFaceResult> volunteerHome() {

        Integer userId = jwtInterceptor.getUserId(request);
        User user = userMapper.selectById(userId);
        if (user == null) {
            return CommonResult.fail("用户不存在，数据库异常");
        }
        UserInfo userInfo =  userInfoMapper.selectByPrimaryKey(userId);
        if (userInfo == null) {
            return CommonResult.fail("数据库异常");
        }
        if(user.getPermission()!=3){
            return CommonResult.fail("权限异常，不是志愿者权限");
        }
        ParentAndVolunteerFaceResult parentAndVolunteerFaceResult = new ParentAndVolunteerFaceResult();
        parentAndVolunteerFaceResult.setUserName(user.getUsername());
        parentAndVolunteerFaceResult.setHeadPicUrl(userInfo.getHeadPicUrl());

        // 下载和喜爱和我的消息， 暂时写死
        parentAndVolunteerFaceResult.setMessageNumber(5);

        return CommonResult.success(parentAndVolunteerFaceResult);
    }

    @Override
    public CommonResult<ChildProfileResult> childProfile() {

        Integer userId = jwtInterceptor.getUserId(request);
        User user = userMapper.selectById(userId);
        if (user == null) {
            return CommonResult.fail("用户不存在，数据库异常");
        }
        UserInfo userInfo =  userInfoMapper.selectByPrimaryKey(userId);
        if (userInfo == null) {
            return CommonResult.fail("数据库异常");
        }
        if(user.getPermission()!=1){
            return CommonResult.fail("权限异常，不是儿童权限");
        }
        ChildProfileResult childProfileResult = new ChildProfileResult();
        childProfileResult.setUserName(userInfo.getUserName());
        childProfileResult.setGender(userInfo.getGender());
        childProfileResult.setNativePlace(userInfo.getNativePlace());
        childProfileResult.setAge(userInfo.getAge());
        childProfileResult.setGrade(userInfo.getGrade());
        childProfileResult.setSign(userInfo.getSign());
        childProfileResult.setHeadPicUrl(userInfo.getHeadPicUrl());


        return CommonResult.success(childProfileResult);

    }

    @Override
    public CommonResult<ParentProfileResult> parentProfile() {

        Integer userId = jwtInterceptor.getUserId(request);

        UserInfo userInfo =  userInfoMapper.selectByPrimaryKey(userId);
        if (userInfo == null) {
            return CommonResult.fail("数据库异常");
        }

        User user = userMapper.selectById(userId);
        if (user == null) {
            return CommonResult.fail("用户不存在，数据库异常");
        }

        if(user.getPermission()!=2){
            return CommonResult.fail("权限异常，不是父母权限");
        }
        ParentProfileResult parentProfileResult = new ParentProfileResult();
        parentProfileResult.setUserName(userInfo.getUserName());
        parentProfileResult.setPhone(user.getPhone());
        parentProfileResult.setGender(userInfo.getGender());
        parentProfileResult.setAge(userInfo.getAge());
        parentProfileResult.setRelation(userInfo.getRelation());
        parentProfileResult.setNativePlace(userInfo.getNativePlace());
        parentProfileResult.setWorkAddress(userInfo.getWorkAddress());
        parentProfileResult.setHomeSituation(userInfo.getHomeSituation());
        parentProfileResult.setSoftwareSituation(userInfo.getSoftwareSituation());
        parentProfileResult.setRemarkChild(userInfo.getRemarkChild());
        parentProfileResult.setRemarkVolunteer(userInfo.getRemarkVolunteer());
        parentProfileResult.setHeadPicUrl(userInfo.getHeadPicUrl());

        return CommonResult.success(parentProfileResult);
    }

    @Override
    public CommonResult<NoData> setVolunteerProfile(HttpServletRequest request, VolunteerProfileResult volunteerProfileResult) {
        Claims claims = TokenUtils.getClaimsFromJwt(request.getHeader("Token"));
        Integer userId = (Integer) claims.get("id");
        User user = userMapper.selectById(userId);
        VolunteerParam volunteer = new VolunteerParam();
        volunteer.setUserName(volunteerProfileResult.getUserName());
        volunteer.setGender(volunteerProfileResult.getGender());
        volunteer.setNativePlace(volunteerProfileResult.getNativePlace());
        volunteer.setAge(volunteerProfileResult.getAge());
        volunteer.setWorkAddress(volunteerProfileResult.getWorkAddress());
        volunteer.setGoodSolveProblems(volunteerProfileResult.getGoodSolveProblems().toString());
        volunteer.setLoginDuration(volunteerProfileResult.getLoginDuration());
        volunteer.setIsOfflineSolution(volunteerProfileResult.getIsOfflineSolution());
        volunteer.setRemarkChild(volunteerProfileResult.getRemarkChild());
        volunteer.setOther(volunteerProfileResult.getOther());
        volunteer.setHeadPicUrl(volunteerProfileResult.getHeadPicUrl());
        try{
            if(user.getIsCertification() == 0){
                userMapper.updateByCertification(userId);
                userInfoMapper.updateVolunteer(userId,volunteer);
                volunteerSortMapper.init(userId);
            }else {
                userInfoMapper.updateVolunteer(userId,volunteer);
            }
        }catch (Exception e){
            e.printStackTrace();
            return CommonResult.fail();
        }

        return CommonResult.success();
    }

    @Override
    public CommonResult<VolunteerProfileResult> getVolunteerProfile(HttpServletRequest request) {
        Claims claims = TokenUtils.getClaimsFromJwt(request.getHeader("Token"));
        Integer userId = (Integer) claims.get("id");
        UserInfo userInfo = userInfoMapper.selectByPrimaryKey(userId);
        User user = userMapper.selectById(userId);
        VolunteerProfileResult volunteerProfileResult = new VolunteerProfileResult();
        volunteerProfileResult.setUserName(userInfo.getUserName());
        volunteerProfileResult.setGender(userInfo.getGender());
        volunteerProfileResult.setNativePlace(userInfo.getNativePlace());
        volunteerProfileResult.setAge(userInfo.getAge());
        volunteerProfileResult.setWorkAddress(userInfo.getWorkAddress());
        volunteerProfileResult.setPhone(user.getPhone());
        List<String> list = Convert.toList(String.class, userInfo.getGoodSolveProblem());
        volunteerProfileResult.setGoodSolveProblems(list);
        volunteerProfileResult.setLoginDuration(userInfo.getLoginDuration());
        volunteerProfileResult.setIsOfflineSolution(userInfo.getIsOfflineSolution());
        volunteerProfileResult.setRemarkChild(userInfo.getRemarkChild());
        volunteerProfileResult.setOther(userInfo.getOther());
        volunteerProfileResult.setHeadPicUrl(userInfo.getHeadPicUrl());
        return CommonResult.success(volunteerProfileResult);
    }

    @Override
    public CommonResult<NoData> setEmergePerson(EmergePersonParam emergePersonParam) {

        Integer childId = jwtInterceptor.getUserId(request);
        User user = userMapper.selectById(childId);
        if (user == null) {
            return CommonResult.fail("用户不存在，数据库异常");
        }
        if(user.getPermission()!=1){
            return CommonResult.fail("权限验证失败，不是小孩账号");
        }

        EmergePerson emergePerson = new EmergePerson();
        emergePerson.setChildId(childId);
        emergePerson.setName(emergePersonParam.getName());
        emergePerson.setPhone(emergePersonParam.getPhone());

        //插入emergePerson表
        int i = emergePersonMapper.insertEmergePerson(emergePerson);
        if(i!=1){
            return CommonResult.fail("插入数据失败");
        }

        return CommonResult.success();
    }

    @Override
    public CommonResult<NoData> reviseEmergePerson(ReviseEmergePersonParam reviseEmergePersonParam) {

        Integer childId = jwtInterceptor.getUserId(request);
        User user = userMapper.selectById(childId);
        if (user == null) {
            return CommonResult.fail("用户不存在，数据库异常");
        }
        if(user.getPermission()!=1){
            return CommonResult.fail("权限验证失败，不是小孩账号");
        }

        EmergePerson emergePerson = new EmergePerson();
        emergePerson.setId(reviseEmergePersonParam.getId());
        emergePerson.setChildId(reviseEmergePersonParam.getChildId());
        emergePerson.setName(reviseEmergePersonParam.getName());
        emergePerson.setPhone(reviseEmergePersonParam.getPhone());

        int i = emergePersonMapper.updateEmergePerson(emergePerson);
        if(i!=1){
            return CommonResult.fail("更新数据库失败");
        }

        return CommonResult.success();
    }

    @Override
    public CommonResult<EmergePersonResult> getEmergePerson() {

        Integer childId = jwtInterceptor.getUserId(request);
        User user = userMapper.selectById(childId);
        if (user == null) {
            return CommonResult.fail("用户不存在，数据库异常");
        }
        if(user.getPermission()!=1){
            return CommonResult.fail("权限验证失败，不是小孩账号");
        }

        List<EmergePerson> emergePersonList = emergePersonMapper.selectAll();
        EmergePersonResult emergePersonResult = new EmergePersonResult();

        emergePersonResult.setEmergePersonList(emergePersonList);

        return CommonResult.success(emergePersonResult);
    }

    @Override
    public CommonResult<NoData> deleteEmergePerson(DeleteEmergePersonParam deleteEmergePersonParam) {

        Integer childId = jwtInterceptor.getUserId(request);
        User user = userMapper.selectById(childId);
        if (user == null) {
            return CommonResult.fail("用户不存在，数据库异常");
        }
        if(user.getPermission()!=1){
            return CommonResult.fail("权限验证失败，不是小孩账号");
        }

        Integer i = emergePersonMapper.deleteByChildIdAndName(childId, deleteEmergePersonParam.getName());
        if(i!=1){
            return CommonResult.fail("刪除联系人失败");
        }

        return CommonResult.success();
    }

}
